import { FC, useEffect, useState, useRef } from 'react';
import { Drawer, Form, Input } from 'antd';
import { layout } from '@/utils/common';
import ButtonWrap from '@/components/commonComponent/buttonWrap/buttonWrap';
import { useLoading } from '@/hooks/baseHook';
import { message, Select } from 'antd';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import { updatedataset, createdataset, algorithmtree } from '@/api/sr-stms';
import { useRequest } from 'umi';

interface Props extends DrawerProps {
  record: any;
  callback: () => void;
}

type DataSourceType = {
  id?: string;
  index: number;
  name: string;
  uuid: string;
};

const APDrawer: FC<Props> = (props) => {
  const { record, visible, onClose, callback } = props;
  const [form] = Form.useForm();
  const [loading, load] = useLoading();
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const { data: datasetTreeList } = useRequest(algorithmtree, {
    formatResult: (res: any) => res.data
  })

  useEffect(() => {
    if (record && visible) {
      form.setFieldsValue(record);
      if (record.details?.length > 0) {
        const mapData = record.details.map((item: any) => {
          return {
            ...item,
            uuid: (Math.random() * 1000000).toFixed(0),
          };
        });
        setDataSource(mapData);
      }
    }
  }, [record, visible, form]);

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="edit"
          className="action-edit"
          onClick={() => {
            action?.startEditable?.(record.uuid);
          }}
        >
          编辑
        </a>,
        <a
          key="del"
          className="action-del"
          onClick={() => {
            setDataSource(
              dataSource.filter((item) => item.uuid !== record.uuid),
            );
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const onFinish = async (vals: any) => {
    if (record) {
      // todo 调用接口编辑
      await load(
        updatedataset({
          ...vals,
          id: record.id,
          algorithm_char_name: record.algorithm_char_name,
        }),
      );
      message.success('编辑成功！');
      callback();
      handleClose();
    } else {
      // todo 调用接口新增
      await load(
        createdataset({
          ...vals,
          // details: dataSource,
        }),
      );
      message.success('新增成功！');
      callback();
      handleClose();
    }
  };

  const handleClose = () => {
    form.resetFields();
    setDataSource([]);
    setEditableRowKeys([]);
    onClose();
  };

  return (
    <Drawer
      width={600}
      title={record ? '编辑' : '新增'}
      visible={visible}
      onClose={handleClose}
    >
      <Form
        form={form}
        {...layout(4)(19)}
        onFinish={onFinish}
        initialValues={{ enabled: true }}
      >
        <Form.Item
          name="dataset_name"
          label="数据集名称"
          rules={[{ required: true, message: '请输入数据集名称！' }]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          name="algorithm_name"
          label="模型标识名称"
          rules={[{ required: true, message: '请输入模型标识名称！' }]}
        >
          <Select>
            {
              datasetTreeList?.map((v: any) => {
                return <Select.Option value={v.algorithm_name} key={v.algorithm_name}>{v.algorithm_name}</Select.Option>
              })
            }
          </Select>
        </Form.Item>
        <ButtonWrap loading={loading} onClose={onClose}></ButtonWrap>
      </Form>
    </Drawer>
  );
};

export default APDrawer;
